<?php
ob_start();
/*
Template Name: Password Reset Template
*/
global $wpdb, $user_ID;

function tg_validate_url() {
	global $post;
	$page_url = esc_url(get_permalink( $post->ID ));
	$urlget = strpos($page_url, "?");
	if ($urlget === false) {
		$concate = "?";
	} else {
		$concate = "&";
	}
	return $page_url.$concate;
}
function custom_wp_mail_from( $original_email_address )
{
	return 'contact@mostcoupon.com';
}
function custom_wp_mail_from_name( $original_email_from )
{
	return 'MostCoupon: Coupon Codes, Discount Codes, Promo Updated Daily!';
}
function for_got_pwd_success($email){
        echo "<div class='success'>We have just sent you an email with Password reset instructions. Please check email address ".$email." then reset your password.</div>";
}
if (!$user_ID) {
    get_header();
    ?>
<div id="content" class="row-fluid">
    <div class="row-fluid content-sidebar">
        <div class="my-account-page lost-password-page">
            <div class="entry-header">
                 <h1 class="entry-title">For got Password</h1>
            </div>
			<?php 
                            
                            if(isset($_GET['key']) && $_GET['action'] == "reset_pwd") {
                                $reset_key = $_GET['key'];
                                $user_login = $_GET['login'];
                                $user_data = $wpdb->get_row($wpdb->prepare("SELECT ID, user_login, user_email FROM $wpdb->users WHERE user_activation_key = %s AND user_login = %s", $reset_key, $user_login));

                                $user_login = $user_data->user_login;
                                $user_email = $user_data->user_email;

                                if(!empty($reset_key) && !empty($user_data)) {
                                        $new_password = wp_generate_password(10, false);
                                        wp_set_password( $new_password, $user_data->ID );
                                        //mailing reset details to the user
                                        $message = __('Your new password for the account at:') . "\r\n\r\n";
                                        $message .= get_option('siteurl') . "\r\n\r\n";
                                        $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
                                        $message .= sprintf(__('Password: %s'), $new_password) . "\r\n\r\n";
                                        $message .= __('You can now change your password at: ') . get_option('siteurl')."/change-password" . "\r\n\r\n";
                                        
                                        add_filter( 'wp_mail_from_name', 'custom_wp_mail_from_name' );
                                        if ( $message && !wp_mail($user_email, 'New password', $message) ) {
                                                echo "<div class='error'>Email failed to send for some unknown reason</div>";
                                                //exit();
                                        }
                                        else {
                                                $redirect_to = site_url().'/change-password';
                                                wp_safe_redirect($redirect_to);
                                                wp_set_auth_cookie($user_data->ID);
                                                //exit();
                                        }
                                }
                                else {
                                    echo "<div class='error'>Not a Valid Key</div>";
                                }
                            }
                            //Have action reset password
                            if($_POST['action'] == "tg_pwd_reset"){
                                $user_input = $wpdb->escape(trim($_POST['user_input']));
                                $user_data = get_userdatabylogin($user_input);
                                $flag = true;
                                if ( !wp_verify_nonce( $_POST['tg_pwd_nonce'], "tg_pwd_nonce")) {
                                    echo "<div class='error'>No trick please!</div>";
                                    $flag = false;
                                }
                                else if(empty($_POST['user_input'])) {
                                        echo "<div class='error'>Please enter your Username or E-mail address!</div>";
                                        $flag = false;
                                    }
                                else if ( strpos($user_input, '@') ) {
                                        $user_data = get_user_by_email($user_input);
                                        if(empty($user_data) || $user_data->caps[administrator] == 1) {
                                            echo "<div class='error'>Invalid E-mail address!</div>";
                                            $flag = false;
                                        }
                                    }
                                else if(empty($user_data) || $user_data->caps[administrator] == 1) {
                                            echo "<div class='error'>Invalid Username!</div>";
                                            $flag = false;
                                        }
                                
                                $user_login = $user_data->user_login;
                                $user_email = $user_data->user_email;
                                
                                $key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));
                                if(empty($key)) {
                                    $key = wp_generate_password(20, false);
                                    $wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login));	
                                }

                                //mailing reset details to the user
                                $message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
                                $message .= get_option('siteurl') . "\r\n\r\n";
                                $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
                                $message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
                                $message .= __('You may clicking on this link or copying and pasting it in your browser to reset your password:') . "\r\n\r\n";
                                $message .= tg_validate_url() . "action=reset_pwd&key=$key&login=" . rawurlencode($user_login) . "\r\n";


                                add_filter( 'wp_mail_from_name', 'custom_wp_mail_from_name' );
                                add_filter( 'wp_mail_from', 'custom_wp_mail_from' );
                                if($flag == true){
                                    if ( $message && !wp_mail($user_email, 'Password Reset Request', $message)) {
                                        echo "<div class='error'>Email failed to send for some unknown reason.</div>";
                                    }
                                    else {
                                       echo "<div class='success'>We have just sent you an email with Password reset instructions.</div>";
                                    }
                                }
                                
                            }
                        ?>
			<form class="for-got-pwd-form" id="wp_pass_reset" action="" method="post">
                            <p class="header-for-got">Lost your password? Please enter your <b>username</b> or <b>email address</b>. You will receive a link to create a new password via email.</p>
                            <p class="lost_password">
                                 <label>Username or email*</label>
                                 <input type="text" class="input-text" name="user_input" value="" /><br />
                                 <input type="hidden" name="action" value="tg_pwd_reset" />
                                 <input type="hidden" name="tg_pwd_nonce" value="<?php echo wp_create_nonce("tg_pwd_nonce"); ?>" />
                                 <input type="submit" id="submitbtn" class="reset_password" name="submit" value="Reset Password" />
                            </p>
			</form>
                        
			<div id="result">
                            <?php
                                  do_action( 'send_mail_success' );
                            ?>
                        </div>
			<script type="text/javascript">  						
                            $("#wp_pass_reset").submit(function() {			
                            $('#result').html('<span class="loading">Validating...</span>').fadeIn();
                            var input_data = $('#wp_pass_reset').serialize();
                            $.ajax({
                            type: "POST",
                            url:  "<?php echo get_permalink( $post->ID ); ?>",
                            data: input_data,
                            success: function(msg){
                            $('.loading').remove();
                            $('<div>').html(msg).appendTo('div#result').hide().fadeIn('slow');
                            }
                            });
                            return false;
                            });
			</script>			
        </div>
    </div>
</div><!-- content -->
<?php
    get_footer();
}
else {
    wp_redirect( home_url() ); exit;
}
ob_flush();
ob_end_clean();
?>